package hu.uszeged.inf.wlab.stunner.database;

import hu.uszeged.inf.wlab.stunner.database.utils.DatabaseConstants;

import java.text.MessageFormat;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * {@link SQLiteOpenHelper} implementation to handle database interactions.
 * 
 * @author szelezsant
 */
public class STUNnerSqliteHelper extends SQLiteOpenHelper {

	/** The name of the database. */
	public static final String DATABASE_NAME = "stunner";
	/** The current version of the database. */
	public static final int DATABASE_VERSION = 1;

	/**
	 * Constructor.
	 * 
	 * @param context - the calling context.
	 */
	public STUNnerSqliteHelper(final Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(final SQLiteDatabase database) {
		Log.i(getClass().getSimpleName(), "Creating tables");

		try {
			database.execSQL(STUNnerContract.Discovery.CREATE_TABLE);
			database.execSQL(STUNnerContract.BatteryInfo.CREATE_TABLE);
			database.execSQL(STUNnerContract.MobileNetInfo.CREATE_TABLE);
			database.execSQL(STUNnerContract.WifiInfo.CREATE_TABLE);
		} catch (final SQLException exception) {
			Log.e(getClass().getSimpleName(), "exeption thrown while creating tables: " + exception);
		}
	}

	@Override
	public void onUpgrade(final SQLiteDatabase database, final int oldVersion, final int newVersion) {
		Log.i(getClass().getSimpleName(), "upgrading database from verion " + oldVersion + " to " + newVersion);
		database.execSQL(MessageFormat.format(DatabaseConstants.DROP_TABLE_PATTERN, STUNnerContract.Discovery.TABLE_NAME));
		database.execSQL(MessageFormat.format(DatabaseConstants.DROP_TABLE_PATTERN, STUNnerContract.BatteryInfo.TABLE_NAME));
		database.execSQL(MessageFormat.format(DatabaseConstants.DROP_TABLE_PATTERN, STUNnerContract.WifiInfo.TABLE_NAME));
		database.execSQL(MessageFormat.format(DatabaseConstants.DROP_TABLE_PATTERN, STUNnerContract.MobileNetInfo.TABLE_NAME));
		onCreate(database);
	}
}
